﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using hotel.DAL;
using hotel.Common;
using hotel.MyUserControl;
using hotel.Win.Common;
using hotel.Win.BaseData;
using hotel.Win.Systems;
using hotel.Win.Report;
using hotel.Win.Query;
using hotel.Win.Member;
using hotel.Win.Subscribe;
using hotel.Win.Report.Excel;

namespace hotel.Win
{
   
    public partial class MainForm : Form
    {        
        MainControl mainControl;
        XTCSModel xtcs = XTCSModel.GetXTCS;
        TimingTask timingTask;
        public MainForm()
        {
            InitializeComponent();
            DisplayStatus();
            ConfigTimingTask();
            LoadToolBarImage();
            MenuGrant();
            if (Configration.IsAutoLoadRoomStatus)
            {
                mainControl = new MainControl();
                mainControl.WindowState = FormWindowState.Maximized;
                mainControl.MdiParent = this;
                mainControl.Show();
            }                       
        }
        /// <summary>
        /// 菜单授权
        /// </summary>
        private void MenuGrant()
        {
            var _context = MyDataContext.GetDataContext;
            var cdqxs = _context.CDQX.Where(p => p.XTYH.ID == UserLoginInfo.UserId);
            
            foreach (var item in cdqxs)
            {
                if (item.SFKY ==1)
                    continue;
                var mi = menuStrip.Items.Find(item.Z_CDBM, true);
                if (mi != null && mi.Length > 0)
                    mi.First().Visible = false;
            }
            //按角色处理的菜单
            mi_xtcz.Visible = UserLoginInfo.HaveRole(EnumRoole.Admin);
            _context.Dispose();
        }
        
        /// <summary>
        /// 加载工具条图片
        /// </summary>
        private void LoadToolBarImage()
        {            
            string path = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\")) + "\\Images\\";
            string fileName = "";
            int index = 1;
            for (int i = 0; i < toolStrip.Items.Count; i++)
            {
                if (toolStrip.Items[i] is ToolStripButton)
                {
                    fileName = path + "tool" + index.ToString() + ".png";
                    toolStrip.Items[i].Image = Image.FromFile(fileName);
                    index++;
                }
            }
        }

        /// <summary>
        /// 配置定时任务
        /// </summary>
        private void ConfigTimingTask()
        {
            string ip = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0].ToString();
            timingTask = new TimingTask();
            //自动夜审,&& 不限制IP   xtcs.ZDYS_IP == ip
            if (xtcs.SF_ZDYS )
                timingTask.StartAutoYeShen();
        }

        /// <summary>
        /// 显现系统状态栏
        /// </summary>
        private void DisplayStatus()
        {
            this.Text = xtcs.JDMC;
            statusStrip.Items[0].Text = "电话：" + xtcs.JDDH;
            statusStrip.Items[1].Text = "操作员：" + UserLoginInfo.UserName;
            statusStrip.Items[2].Text = "营业日期：" + xtcs.YYRQ;
            statusStrip.Items[3].Text = "本机IP：" + System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0].ToString();
        }       

        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;
            }
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            sbtnexit_Click(this, null);
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void tmi_about_Click(object sender, EventArgs e)
        {
            new Common.AboutBox().ShowDialog();
        }

        #region 窗口操作
        /// <summary>
        /// 保证只打开一个子窗口
        /// </summary>
        /// <param name="ChildTypeString"></param>

        private void OpenWindow(string ChildTypeString)
        {
            Form fChild = null;

            if (!ContainMDIChild(ChildTypeString))
            {
                // Get current process assembly
                Assembly assembly = Assembly.GetExecutingAssembly();

                // Create data type using type string
                Type typForm = assembly.GetType(ChildTypeString);

                // Create object using type's "InvokeMember" method
                Object obj = typForm.InvokeMember(
                    null,
                    BindingFlags.DeclaredOnly |
                    BindingFlags.Public | BindingFlags.NonPublic |
                    BindingFlags.Instance | BindingFlags.CreateInstance,
                    null,
                    null,
                    null);

                // Show child form 
                if (obj != null)
                {
                    fChild = obj as Form;
                    //Rectangle rect = this.ClientRectangle;
                    //fChild.SetBounds(rect.Left, rect.Top, rect.Width - 5, rect.Height - 5);
                    fChild.WindowState = FormWindowState.Maximized;
                    fChild.MdiParent = this;
                    fChild.Show();
                    fChild.Focus();
                }
            }
        }

        private void OpenWindowNormal(string ChildTypeString)
        {
            Form fChild = null;

            if (!ContainMDIChildNormal(ChildTypeString))
            {
                // Get current process assembly
                Assembly assembly = Assembly.GetExecutingAssembly();

                // Create data type using type string
                Type typForm = assembly.GetType(ChildTypeString);

                // Create object using type's "InvokeMember" method
                Object obj = typForm.InvokeMember(
                    null,
                    BindingFlags.DeclaredOnly |
                    BindingFlags.Public | BindingFlags.NonPublic |
                    BindingFlags.Instance | BindingFlags.CreateInstance,
                    null,
                    null,
                    null);

                // Show child form 
                if (obj != null)
                {
                    fChild = obj as Form;
                    fChild.MdiParent = this;
                    fChild.Show();
                    fChild.Focus();
                }
            }
        }

        /// <summary>
        /// Search mdi child form by specific type string
        /// </summary>
        /// <param name="ChildTypeString"></param>
        /// <returns></returns>
        private bool ContainMDIChild(string ChildTypeString)
        {
            Form fMDIChild = null;
            foreach (Form f in this.MdiChildren)
            {
                if (f.GetType().ToString() == ChildTypeString)
                {
                    // found it 
                    fMDIChild = f;
                    break;
                }
            }

            // Show the exist form
            if (fMDIChild != null)
            {
                Rectangle rect = this.ClientRectangle;
                fMDIChild.SetBounds(rect.Left, rect.Top, rect.Width - 5, rect.Height - 5);
                fMDIChild.TopMost = true;
                fMDIChild.Show();
                fMDIChild.Focus();
                return true;
            }
            else
            {
                return false;
            }
        }
        private bool ContainMDIChildNormal(string ChildTypeString)
        {
            Form fMDIChild = null;
            foreach (Form f in this.MdiChildren)
            {
                if (f.GetType().ToString() == ChildTypeString)
                {
                    // found it 
                    fMDIChild = f;
                    break;
                }
            }

            // Show the exist form
            if (fMDIChild != null)
            {
                fMDIChild.TopMost = true;
                fMDIChild.Show();
                fMDIChild.Focus();
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 外部dll的窗体
        /// </summary>
        /// <param name="fChild"></param>
        private void OpenWindow2(Form fChild)
        {
            if (!ContainMDIChild(fChild.GetType().ToString()))
            {
                fChild.WindowState = FormWindowState.Maximized;
                fChild.MdiParent = this;
                fChild.Show();
                fChild.Focus();
            }
        }

        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        #endregion

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //var frm = new Form3();
            //frm.Show();
            this.OpenWindow(typeof(Form1).ToString());
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //LoadHouse();
        }

        /// <summary>
        /// 加载所有房间
        /// </summary>
        private void LoadHouse()
        {

            //数据
            //var houses = new Dictionary<string, ucRoom>();
            //houses.Add("001", new ucRoom("001"));
            //houses.Add("002", new ucRoom("002"));
            //houses.Add("003", new ucRoom("003"));
            //houses.Add("004", new ucRoom("004"));
            //houses.Add("005", new ucRoom("005"));
            //houses.Add("006", new ucRoom("006"));
            //houses.Add("007", new ucRoom("007"));
            ////填充到panel
            //tlpHouse.Controls.Clear();
            //tlpHouse.ColumnStyles.Clear();
            //tlpHouse.RowStyles.Clear();
            //tlpHouse.ColumnCount = houses.Count+1;
            //var hcol = new ColumnStyle(SizeType.Absolute, 50);
            //tlpHouse.ColumnStyles.Add(hcol);
            //foreach (var h in houses)
            //{
            //    var colstyle = new ColumnStyle(SizeType.Absolute,h.Value.Width);
            //    tlpHouse.ColumnStyles.Add(colstyle);
            //}
            //tlpHouse.RowCount = 2;
            //tlpHouse.RowStyles.Add(new RowStyle(SizeType.Absolute,23));
            //tlpHouse.RowStyles.Add(new RowStyle(SizeType.Absolute, 80));

            //tlpHouse.Controls.Add(new Button() { Text = "18/F" }, 0, 1);
            //int col = 1;
            //foreach (var h in houses)
            //{
            //    tlpHouse.Controls.Add(new Button() { Text= h.Key }, col, 0);
            //    tlpHouse.Controls.Add(h.Value, col, 1);
            //    col++;
            //}
        }

        private void helpToolStripButton_Click(object sender, EventArgs e)
        {

        }

        private void mi_kfpz_Click(object sender, EventArgs e)
        {
            this.OpenWindow(typeof(BaseData.kypzFrm).ToString());
            //var frm =new hotel.Win.BaseData.kypzFrm();
            //frm.MdiParent = this;
            //frm.Show();
            //Form childForm = new Form();
            //childForm.MdiParent = this;
            //childForm.Text = "窗口 " + childFormNumber++;
            //childForm.Show();
        }

        private void sbtnssft_Click(object sender, EventArgs e)
        {
            //实时房态窗口不能关闭，很多状态没有处理好
            if (mainControl == null)
            {
                mainControl = new MainControl();
                mainControl.WindowState = FormWindowState.Maximized;
                mainControl.MdiParent = this;
                mainControl.Show();
            }
            else
            {
                this.ActivateMdiChild(mainControl);
            }
        }

        private void micydm_Click(object sender, EventArgs e)
        {
            this.OpenWindow(typeof(xtcydmFrm).ToString());
        }

        private void mi_xtyhxq_Click(object sender, EventArgs e)
        {
            this.OpenWindow(typeof(xtyhqxFrm).ToString());
        }

        private void mi_xfxm_Click(object sender, EventArgs e)
        {
            this.OpenWindow(typeof(xfxmFrm).ToString());
        }

        private void mi_xydwgl_Click(object sender, EventArgs e)
        {
            this.OpenWindow(typeof(xydwFrm).ToString());
        }

        private void tmi_xydwzw_Click(object sender, EventArgs e)
        {
            this.OpenWindow(typeof(GuaZhangDW).ToString());
        }

        private void sbtnjztf_Click(object sender, EventArgs e)
        {
            mainControl.JZTFMenuMethod();
        }
        private void sbtnbjya_Click(object sender, EventArgs e)
        {
            mainControl.YJCLMenuMethod();
        }

        private void sbtnxfrd_Click(object sender, EventArgs e)
        {
            mainControl.XFRDMenuMethod();
        }

        private void sbtnBjdtf_Click(object sender, EventArgs e)
        {
           
        }

        #region 主菜单或工具栏--共用房态菜单事件

        private void tmi_xyd_Click(object sender, EventArgs e)
        {
            mainControl.NewYDMenuMethod();
        }

        private void tmi_krdj_Click(object sender, EventArgs e)
        {
            mainControl.KRTJMenuMethod();
        }

        private void tmi_krxx_Click(object sender, EventArgs e)
        {
            mainControl.KRXXMenuMethod();
        }

        private void tmi_krhf_Click(object sender, EventArgs e)
        {
            mainControl.KRHFMenuMethod();
        }
        //删除客单
        private void mi_sckd_Click(object sender, EventArgs e)
        {
            mainControl.SCKRMenuMethod();
        }
        //房态修改
        private void tmi_ftxg_Click(object sender, EventArgs e)
        {
            mainControl.FTXGMenuMethod();
        }
        
        private void tmi_wxjl_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new WieXiuFangFrm());
        }
        //交班
        private void tmi_jbgl_Click(object sender, EventArgs e)
        {
            var frm = new Member.JiaoBanFrm();
            frm.ShowDialog();
        }
        #endregion

        private void sbtnexit_Click(object sender, EventArgs e)
        {
            //initMenu();
            if (MessageBox.Show("你确定退出酒店前台管理系统吗？", hotel.Common.SysConsts.SysWarningCaption, MessageBoxButtons.OKCancel) != DialogResult.OK)
                return;
            this.Close();
            
        }
        /// <summary>
        /// 初始化菜单-只支持2级，再调用maincontrol.initMenu
        /// </summary>
        private void initMenu()
        {
            var _context = new hotel.DAL.hotelEntities();
            //var xtyh = _context.XTYH.First(p => p.ID == SysConsts.SystemAdminId);
            int zxh;
            string f_cdbm;
            foreach (ToolStripItem pitem in menuStrip.Items)
            {
                if (pitem.Name == "windowsMenu" || pitem.Name == "helpMenu")
                    continue;
                zxh = 1;
                f_cdbm = pitem.Name;
                var pmodel = new CDQX { YHID = SysConsts.SystemAdminId };
                pmodel.CDMC = pitem.Text;
                pmodel.F_CDBM = "";
                pmodel.SFKY = 1;
               // pmodel.XTYH = xtyh;
                pmodel.Z_CDBM = pitem.Name;
                pmodel.ZXH = zxh;
                _context.CDQX.Add(pmodel);
                foreach (ToolStripItem item in (pitem as ToolStripMenuItem).DropDownItems)
                {
                    if (!(item is ToolStripMenuItem))
                        continue;
                    var model = new CDQX { YHID = SysConsts.SystemAdminId };
                    model.CDMC = item.Text;
                    model.F_CDBM = f_cdbm;
                    model.SFKY = 1;
                   // model.XTYH = xtyh;
                    model.Z_CDBM = item.Name;
                    model.ZXH = zxh;
                    _context.CDQX.Add(model);
                    zxh++;
                }
                _context.SaveChanges();
            }
        }

        //不结帐退房恢复入住
        private void tmi_bjztf_hf_Click(object sender, EventArgs e)
        {
            var frm = new Subscribe.rzhfMaintain();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                mainControl.RefreshRoomFromDataBase(frm.RoomIds);
            }
            
        }
        
        private void tmiFrzxf_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new FeiRuZhuXiaoFei());
        }
        private void tmi_yjsh_Click(object sender, EventArgs e)
        {
#if TRIAL
            new TrialForm().ShowDialog();
            return;
#else
            var _context = MyDataContext.GetDataContext;
            if (_context.YSJL_Check().Single() != 0)
            {
                MessageBox.Show(text:"今天已经夜审，不需要再次夜审");
                return;
            }
            
            if (MessageBox.Show("当前营业日期:" + XTCSModel.GetXTCS.YYRQ + "\n每天只能进行一次夜审，夜审后数据不能更改\n系统默认设置的夜审时间是每天" + XTCSModel.GetXTCS.ZDYS_SJ
                     + "前\n你确定现在开始夜审吗？", hotel.Common.SysConsts.SysWarningCaption, MessageBoxButtons.OKCancel) != DialogResult.OK)
                return;
            _context.YSJL_Create(UserLoginInfo.FullName,"手工夜审");
            _context.Dispose();
            XTCSModel.GetXTCS.Reset();
           
            //写系统日志
            var log = Log.Instance;
            log.Abstract = hotel.Common.LogAbstractEnum.手工夜审;
            log.Message = "手工夜审,当前营业日期:" + XTCSModel.GetXTCS.YYRQ;
            log.Info();
            #region 日志纪录
            var logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.手工夜审;
            logInfo.Type = LogTypeEnum.一般操作;
            logInfo.Message = "手工夜审";
            logInfo.Save();
            #endregion
            MessageBox.Show("当前营业日期:" + XTCSModel.GetXTCS.YYRQ + "\n夜审完成，系统将自动退出!");
            Application.Exit();
#endif
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!UserLoginInfo.HaveRole(EnumRoole.QianTaiJingLi))
            {
                MessageBox.Show("只有高于前台经理的角色才可以操作");
                return;
            }
            var frm = new Systems.xtszFrm();
            frm.ShowDialog();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var log = Log.Instance;
            log.Abstract = LogAbstractEnum.退出系统;
            log.Message = "退出系统";
            log.Info();
            Properties.Settings.Default.UserId = UserLoginInfo.UserId;
            Properties.Settings.Default.Save();
        }

        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //new Form1().ShowDialog();
            //this.OpenWindow(typeof(xtyhqxFrm).ToString());
        }

        private void mi_ydkrlb_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new YudingFrm());
        }

        private void mi_zzkrlb_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new ZaiZhuFrm());
        }

        private void mi_jzkrlb_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new JieZhangFrm());
        }
        //预离开
        private void tmirlryb_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new YulidianFrm());
        }
        private void tmi_ysjl_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new YeShengJLFrm());
        }
        //系统日志
        private void tmi_ccrz_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new RiZhiFrm());
        }

        private void tmi_hyklx_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new HuiYuanTypeFrm());
        }
        private void tmiccrz_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new CaoZuorzFrm());
        }
        //客历查询
        private void tmi_kscx_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new KeShiViewFrm());
            
        }
        #region 报表事件

        private void tmi_hyk_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new HuiYuanFrm());
        }

        /// <summary>
        /// 会议室管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmi_hysgl_Click(object sender, EventArgs e)
        {
            this.OpenWindow2(new HuiYiShiFrm());
        }       
       
        private void tmi_skydb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowSanKeYuDingReport();
        }


        private void tim_tdydb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowTuanDuiYuDingReport();
        }

       
        private void tmi_zzkrb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowRuZhuRenYuanReport();
        }
       

        private void tim_wxfjb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowWeiXiuFangReport();
        }
        private void tmi_jzryb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowJieZhangRenYuanReport();
        }
        
        private void tmi_zzryfzbb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowZaiZhuFangZuReport();
        }

        private void tmi_xtgsrzb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowXieYiGongSiRZReport();
        }

        private void tmi_fjztbb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowFangJiZhuangTaiReport();
        }
       
        private void tmi_xfflhzb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowXiaoFeiHuiZongReport();
        }
       
        private void tmi_xfmxbb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowXiaoFeiMingXiReport();
        }

        private void tmi_yjmxbb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowYaJinMingXiReport();
        }

        private void tmi_krzfyebb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowZhangHuYueReport();
        }
                     
        private void tmi_xygxzfb_Click(object sender, EventArgs e)
        {
            ReportEntry.ShowXieYiDanWeiZFReport();
        }
        private void tirbaob_Click(object sender, EventArgs e)
        {
           // ExcelReport.ImportZongBiao(DateTime.Now.Date);
            //营业日报,交款表
            ReportEntry.ShowYingYeRiBaoReport(0);
        }
       #endregion  

        private void sbtnFTXG_Click(object sender, EventArgs e)
        {

        }

        private void tmi_registe_Click(object sender, EventArgs e)
        {
            var frm = new RegisterForm();
            frm.ShowDialog();
        }
    }
}
